﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using ERCS.Model;


namespace ERCS.ViewModel.BasicData.CityVMs
{
    public partial class CityVM : BaseCRUDVM<City>
    {
        public List<ComboSelectListItem> AllParents { get; set; }

        public CityVM()
        {
            SetInclude(x => x.Parent);
        }

        protected override void InitVM()
        {
            AllParents = DC.Set<City>().GetSelectListItems(LoginUserInfo?.DataPrivileges, null, y => y.Name);
        }

        public override void DoAdd()
        {           

            using (var transaction = DC.BeginTransaction())
            {
                try
                {
                    base.DoAdd();
                    HospitalVMs.HospitalVM hvm = new HospitalVMs.HospitalVM();
                    hvm.CopyContext(this);
                    hvm.SetEntity(new Hospital
                    {
                        Name = Entity.Name + "默认医院",
                        LocationId = Entity.ID,
                        Level = HospitalLevel.Class1
                    });
                    hvm.Validate();
                    hvm.DoAdd();

                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    MSD.AddModelError(" no123", "添加失败");
                }
            }

        }

        public override void DoEdit(bool updateAllFields = false)
        {
            base.DoEdit(updateAllFields);
        }

        public override void DoDelete()
        {
            DC.CascadeDelete(Entity);
            var toedit = DC.Set<Patient>().Where(x => x.Hospital.LocationId == Entity.ID).Select(x => x.ID).ToList();
            foreach (var item in toedit)
            {
                var patient = new Patient { ID = item,HospitalId = null };
                DC.UpdateProperty(patient, x => x.HospitalId);
            }
            base.DoDelete();
        }
    }
}
